#include "../../include/Tileset/tileset.hpp"
#include "../../include/Tileset/tilesetTile.hpp"
#include "../../include/Tileset/tilesetImage.hpp"
#include "../../include/Tileset/tilesetProperties.hpp"
#include <tinyxml.h>
namespace Tmx{

Tileset::Tileset()
{
  firstGid = 0;
  tileWidth = 0;
  tileHeight = 0;
  margin = 0;
  spacing = 0;
  image = NULL;
  properties = NULL;
}

Tileset::~Tileset()
{
	if (image != 0)
		delete image;
	std::vector<Tile *>::iterator tIter;
	for (tIter = tiles.begin(); tIter != tiles.end(); tIter++) {
		Tile *tile = *tIter;
		delete tile;
	}
}

void Tileset::parse(TiXmlNode *tilesetNode)
{
	TiXmlElement *tilesetElement = tilesetNode->ToElement();
	tilesetElement->Attribute("firstgid", &firstGid);
	tilesetElement->Attribute("tilewidth", &tileWidth);
	tilesetElement->Attribute("tileheight", &tileHeight);
	tilesetElement->Attribute("margin", &margin);
	tilesetElement->Attribute("spacing", &spacing);
	name = tilesetElement->Attribute("name");
	TiXmlNode *imageNode = tilesetNode->FirstChild("image");
	if (imageNode) {
		image = new Image();
		image->parse(imageNode);
	}
	TiXmlNode *tileNode = tilesetNode->FirstChild("tile");
	while (tileNode) {
		Tile *tile = new Tile();
		tile->parse(tileNode);
		tiles.push_back(tile);
		tileNode = tilesetNode->IterateChildren("tile", tileNode);
	}
	// TODO implement properties
	TiXmlNode *propertiesNode = tilesetNode->FirstChild("properties");
	if (propertiesNode != 0) {
	  properties->parse(propertiesNode);
	}
}
} // namespace Tmx
